<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item
					:label="$t('common.belong_merchant') + ':'"
					prop="merchantId"
					class="flex-row-container"
					label-width="77px"
				>
					<merchant-select
						v-model="queryData.merchantId"
						:placeholder="$t('common.select_all')"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="
						$t('operation.announcement.announcement_title') + ':'
					"
					prop="title"
					class="flex-row-container"
					label-width="77px"
				>
					<el-input
						v-model="queryData.title"
						clearable
						:maxlength="100"
						size="medium"
						:placeholder="$t('common.please_enter')"
					></el-input>
				</el-form-item>

				<el-form-item
					:label="
						$t('operation.announcement.announcement_time') + ':'
					"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.aging"
						style="width: 300px"
						clearable
						:placeholder="$t('common.select_all')"
						:popper-append-to-body="false"
					>
						<el-option
							v-for="item in announcementAgingTypes"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="$t('operation.send_device') + ':'"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.terminal"
						multiple
						collapse-tags
						:placeholder="$t('common.select_all')"
						:popper-append-to-body="false"
					>
						<el-option
							v-for="item in loginDeviceType"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="$t('operation.announcement.tag') + ':'"
					class="flex-row-container"
					label-width="55px"
				>
					<el-select
						v-model="queryData.tag"
						clearable
						style="width: 300px"
						:placeholder="$t('common.select_all')"
						:popper-append-to-body="false"
					>
						<el-option
							v-for="item in tagTypes"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="$t('common.status') + ':'"
					class="flex-row-container"
					label-width="55px"
				>
					<el-select
						v-model="queryData.status"
						clearable
						:placeholder="$t('common.select_all')"
					>
						<el-option
							:key="0"
							:value="0"
							:label="$t('common.status_disabled')"
						></el-option>
						<el-option
							:key="1"
							:value="1"
							:label="$t('common.status_turn_on')"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select
						v-model="queryData.opType"
						:placeholder="$t('common.please_choose')"
						style="width: 150px"
					>
						<el-option
							:label="$t('common.createBy')"
							value="0"
						></el-option>
						<el-option
							:label="$t('common.last_updateBy')"
							value="1"
						></el-option>
					</el-select>
					<el-input
						v-model="queryData.opName"
						size="medium"
						:placeholder="$t('common.please_enter')"
						clearable
						style="width: 278px"
						v-input="{ name: 'num_alp' }"
					></el-input>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('502011')"
						type="warning"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="openCreateOrEditDialog()"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="list"
				highlight-current-row
				:header-cell-style="getRowClass"
				:max-height="tableHeight"
			>
				<el-table-column
					prop="title"
					align="center"
					width="200px"
					:label="$t('operation.announcement.announcement_title')"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>
							{{ scope.row.title || '-' }}
						</span>
						<!--<p v-if="scope.row.titleEn">
									{{ $t('common.en') }}：{{
										scope.row.titleEn || '-'
									}}
								</p>
								<p v-if="scope.row.titleTh">
									{{ $t('common.th') }}：{{
										scope.row.titleTh || '-'
									}}
								</p>
								<p v-if="scope.row.titleVi">
									{{ $t('common.vn') }}：{{
										scope.row.titleVi || '-'
									}}
								</p>-->
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('operation.announcement.announcement_content')"
					width="200px"
					prop="content"
				>
					<template slot-scope="scope">
						<!-- <span>
								{{ scope.row.content || '-' }}
							</span> -->
						<el-tooltip
							v-if="scope.row.content.length > 12"
							class="item"
							effect="dark"
							placement="top"
						>
							<div class="tooltip-content" slot="content">
								{{ scope.row.content || '-' }}
							</div>
							<div class="tooltip-trigger">
								{{ scope.row.content }}
							</div>
						</el-tooltip>
						<span v-else>
							{{ scope.row.content || '-' }}
						</span>
						<!--<p v-if="scope.row.contentEn">
									{{ $t('common.en') }}：{{
										scope.row.contentEn || '-'
									}}
								</p>
								<p v-if="scope.row.contentTh">
									{{ $t('common.th') }}：{{
										scope.row.contentTh || '-'
									}}
								</p>
								<p v-if="scope.row.contentVi">
									{{ $t('common.vn') }}：{{
										scope.row.contentVi || '-'
									}}
								</p>-->
					</template>
				</el-table-column>
				<el-table-column
					prop="tag"
					align="center"
					:label="$t('operation.announcement.tag')"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span v-if="scope.row.tag === 0">
							{{ $t('operation.announcement.none') }}
						</span>
						<span v-else-if="scope.row.tag === 1">
							{{ $t('operation.announcement.important') }}
						</span>
						<span v-else-if="scope.row.tag === 2">
							{{ $t('operation.announcement.push_top') }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('operation.send_device')"
					width="290px"
					prop="terminal"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>
							{{ filterTerminal(scope.row.terminal) }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('operation.announcement.announcement_time')"
					prop="aging"
					show-overflow-tooltip
				>
					<template v-if="scope.row.aging" slot-scope="scope">
						{{
							scope.row.aging === 1
								? $t('operation.limited_time')
								: $t('operation.permanent')
						}}
					</template>
					<span v-else>-</span>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('operation.announcement.added_time')"
					prop="upTime"
					width="155px"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.upTime || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					:label="$t('operation.announcement.shelf_time')"
					prop="downTime"
					width="155px"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.aging === 1 ? scope.row.downTime : '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="status"
					align="center"
					width="90px"
					:label="$t('common.status')"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<div v-if="scope.row.status === 0" class="disableRgba">
							{{ $t('common.status_disabled') }}
						</div>
						<div
							v-else-if="scope.row.status === 1"
							class="normalRgba"
						>
							{{ $t('common.status_turn_on') }}
						</div>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="createdBy"
					align="center"
					:label="$t('common.createBy')"
					width="120"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.createdBy || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="createdAt"
					align="center"
					:label="$t('common.createAt')"
					width="155px"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.createdAt || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="updatedBy"
					align="center"
					:label="$t('common.last_updateBy')"
					width="120"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="updatedAt"
					align="center"
					:label="$t('common.last_updateAt')"
					width="155px"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="operating"
					align="center"
					width="240px"
					:label="$t('common.actions')"
				>
					<template slot-scope="scope">
						<el-button
							v-if="
								scope.row.status === 1 &&
								hasPermission('502013')
							"
							:disabled="loading"
							type="danger"
							size="medium"
							class="noicon"
							@click="changeStatus(scope.row)"
						>
							{{ $t('common.disabled') }}
						</el-button>
						<el-button
							v-if="
								scope.row.status !== 1 &&
								hasPermission('502013')
							"
							:disabled="loading"
							type="success"
							size="medium"
							class="noicon"
							@click="changeStatus(scope.row)"
						>
							{{ $t('common.start_up') }}
						</el-button>
						<el-button
							v-if="hasPermission('502012')"
							:disabled="scope.row.status === 1"
							type="primary"
							icon="el-icon-edit"
							size="medium"
							@click="openCreateOrEditDialog(scope.row)"
						>
							{{ $t('common.edit') }}
						</el-button>
						<el-button
							v-if="
								hasPermission('502014') &&
								scope.row.status !== 1
							"
							:disabled="scope.row.status === 1"
							type="danger"
							icon="el-icon-delete"
							size="medium"
							@click="deleteBtn(scope.row)"
						>
							{{ $t('common.delete') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			:title="dialogType"
			:visible.sync="dialogFormVisible"
			:width="$i18n.locale === 'zh_CN' ? `810px` : `910px`"
			center
			class="dialog_style"
			@close="clear"
		>
			<el-form
				ref="formSub"
				:model="dialogForm"
				:rules="dataRule"
				label-width="auto"
			>
				<el-form-item
					:label="$t('common.choose_merchant') + ':'"
					class="tagheight"
					prop="merchantId"
				>
					<merchant-select
						ref="merchantSelect"
						v-model="dialogForm.merchantId"
						:placeholder="$t('common.please_choose')"
						:merchantInfo.sync="merchantInfoA"
						:disabled="dialogType === $t('common.edit')"
						@change="handleMerchantIdChange"
					></merchant-select>
				</el-form-item>
				<h4 style="text-align: center">
					{{ $t('operation.announcement.announcement_title') }}
				</h4>
				<el-form-item
					:label="$t('common.zh') + ':'"
					class="tagheight"
					prop="title"
				>
					<el-input
						v-model="dialogForm.title"
						:placeholder="$t('common.please_enter')"
						:maxlength="100"
						show-word-limit
						clearable
						v-input="{ name: 'symbols' }"
						autocomplete="off"
					></el-input>
				</el-form-item>
				<!-- <el-form-item
						v-if="filterLanguages('en_US')"
						:label="$t('common.en') + ':'"
						class="tagheight"
						prop="titleEn"
					>
						<el-input
							v-model="dialogForm.titleEn"
							:placeholder="$t('common.please_enter')"
							maxlength="100"
							show-word-limit
							clearable
							autocomplete="off"
						></el-input>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('th_TH')"
						:label="$t('common.th') + ':'"
						class="tagheight"
						prop="titleTh"
					>
						<el-input
							v-model="dialogForm.titleTh"
							:placeholder="$t('common.please_enter')"
							maxlength="100"
							show-word-limit
							clearable
							autocomplete="off"
						></el-input>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('vi_VN')"
						:label="$t('common.vn') + ':'"
						class="tagheight"
						prop="titleVi"
					>
						<el-input
							v-model="dialogForm.titleVi"
							:placeholder="$t('common.please_enter')"
							maxlength="100"
							show-word-limit
							clearable
							autocomplete="off"
						></el-input>
					</el-form-item> -->
				<el-divider></el-divider>
				<h4 style="text-align: center">
					{{ $t('operation.announcement.announcement_content') }}
				</h4>
				<el-form-item
					:label="$t('common.zh') + ':'"
					class="tagheight"
					prop="content"
				>
					<el-input
						v-model="dialogForm.content"
						:placeholder="$t('common.please_enter')"
						:maxlength="2000"
						clearable
						show-word-limit
						autocomplete="off"
						type="textarea"
					></el-input>
				</el-form-item>
				<!-- <el-form-item
						v-if="filterLanguages('en_US')"
						:label="$t('common.en') + ':'"
						class="tagheight"
						prop="contentEn"
					>
						<el-input
							v-model="dialogForm.contentEn"
							:placeholder="$t('common.please_enter')"
							maxlength="2000"
							clearable
							type="textarea"
							show-word-limit
						></el-input>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('th_TH')"
						:label="$t('common.th') + ':'"
						class="tagheight"
						prop="contentTh"
					>
						<el-input
							v-model="dialogForm.contentTh"
							:placeholder="$t('common.please_enter')"
							maxlength="2000"
							clearable
							type="textarea"
							show-word-limit
						></el-input>
					</el-form-item>
					<el-form-item
						v-if="filterLanguages('vi_VN')"
						:label="$t('common.vn') + ':'"
						class="tagheight"
						prop="contentVi"
					>
						<el-input
							v-model="dialogForm.contentVi"
							:placeholder="$t('common.please_enter')"
							maxlength="2000"
							clearable
							type="textarea"
							show-word-limit
						></el-input>
					</el-form-item> -->
				<el-divider></el-divider>
				<el-form-item
					:label="$t('operation.announcement.tag') + ':'"
					class="tagheight"
					prop="tag"
				>
					<el-select
						v-model="dialogForm.tag"
						:placeholder="$t('common.select_all')"
						:popper-append-to-body="false"
					>
						<el-option
							v-for="item in tagTypes"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
					<span class="el-form-item__error">
						{{ $t('operation.announcement.tag_tips') }}
					</span>
				</el-form-item>
				<el-form-item
					:label="$t('operation.send_device') + ':'"
					class="tagheight"
					prop="terminal"
				>
					<el-select
						v-model="dialogForm.terminal"
						multiple
						:placeholder="$t('common.please_choose')"
						:popper-append-to-body="false"
					>
						<el-option
							v-for="item in loginDeviceType"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="
						$t('operation.announcement.announcement_time') + ':'
					"
					class="tagheight"
					prop="aging"
				>
					<el-select
						v-model="dialogForm.aging"
						:placeholder="$t('common.please_choose')"
						:popper-append-to-body="false"
					>
						<el-option
							v-for="item in announcementAgingTypes"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="状态:" class="tagheight">
						<el-select
							v-model="dialogForm.status"
							clearable
							:placeholder="$t('common.please_choose')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="item in status"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item> -->
				<el-form-item
					:label="$t('operation.announcement.added_time') + ':'"
					prop="onlineTime"
					:rules="[
						{
							required: true,
							validator: validateUpTime,
							trigger: 'blur'
						}
					]"
				>
					<el-date-picker
						v-model="onlineTime"
						size="medium"
						format="yyyy-MM-dd HH:mm:ss"
						:picker-options="dateNow"
						type="datetime"
						:clearable="false"
						@change="changeTime"
					></el-date-picker>
					<!-- <span
							v-show="errTime"
							class="el-form-item__error"
							style="margin-top:20px"
						>
							{{ $t('operation.announcement.time_tips1') }}
						</span> -->
				</el-form-item>
				<el-form-item
					v-if="dialogForm.aging === 1"
					:label="$t('operation.announcement.shelf_time') + ':'"
					prop="offlineTime"
					:rules="[
						{
							required: true,
							validator: validateDownTime,
							trigger: 'blur'
						}
					]"
				>
					<el-date-picker
						v-model="offlineTime"
						size="medium"
						format="yyyy-MM-dd HH:mm:ss"
						:picker-options="dateEnd"
						type="datetime"
						:clearable="false"
						@change="changeTime"
					></el-date-picker>
					<!-- <span
							v-show="errTime"
							class="el-form-item__error"
							style="margin-top:20px"
						>
							{{ $t('operation.announcement.time_tips2') }}
						</span> -->
				</el-form-item>
				<el-form-item
					:label="$t('operation.announcement.view_config') + ':'"
					:rules="[
						{
							required: true,
							message: this.$t('operation.announcement.display'),
							trigger: 'change'
						}
					]"
					prop="display"
				>
					<el-checkbox-group
						style="width: 80%; text-align: left"
						v-model="dialogForm.display"
					>
						<!-- todo 一期暂时禁用佣金契约 -->
						<el-checkbox label="FRONT_PAGE">
							{{ $t('operation.announcement.home_page') }}
						</el-checkbox>
						<el-checkbox label="MESSAGE_CENTER">
							{{ $t('operation.announcement.msg_center') }}
						</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button
					:loading="loading"
					type="primary"
					@click="subAddOrEidt"
				>
					{{ $t('common.save') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'

const endTime = dayjs().endOf('date')
export default {
  name: routerNames.announcement,
  components: {
    MainContent
  },
  mixins: [list],
  data() {
    return {
      tableHeight: 480,
      otherDependenComponents: [],
      merchantInfoA: {
        languages: 'zh_CN'
      },
      pageNum: 1,
      pageSize: 100,
      total: 0,
      queryData: {
        merchantId: undefined,
        terminal: [],
        aging: undefined,
        opType: '0',
        opName: undefined,
        tag: undefined,
        status: undefined
      },
      rowData: {},
      dialogFormVisible: false,
      dialogForm: {
        merchantId: '',
        tag: 1,
        terminal: ['1', '2', '3', '4', '5'],
        aging: 1,
        title: '',
        titleEn: '',
        titleTh: '',
        titleVi: '',
        content: '',
        contentEn: '',
        contentTh: '',
        contentVi: '',
        status: 0,
        display: []
      },
      dialogType: '',
      onlineTime: Date.now(),
      offlineTime: endTime,
      dateNow: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
      dateEnd: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      }
    }
  },
  computed: {
    operateStatus() {
      return this.globalDics.operateStatus || []
    },
    loginDeviceType() {
      return this.globalDics.loginDeviceType || []
    },
    announcementAgingTypes() {
      // return this.globalDics.announcementAgingType
      return [
        {
          code: 1,
          description: this.$t('operation.limited_time')
        },
        {
          code: 2,
          description: this.$t('operation.permanent')
        }
      ]
    },
    operateTypes() {
      // return this.globalDics.operateType
      return [
        { code: 1, description: this.$t('common.createBy') },
        { code: 2, description: this.$t('common.last_updateBy') }
      ]
    },
    tagTypes() {
      // return this.globalDics.tagType
      return [
        {
          code: 0,
          description: this.$t('operation.announcement.none')
        },
        {
          code: 1,
          description: this.$t('operation.announcement.important')
        },
        {
          code: 2,
          description: this.$t('operation.announcement.push_top')
        }
      ]
    },
    status() {
      // return this.globalDics.status
      return [
        { code: 0, description: this.$t('common.status_disabled') },
        { code: 1, description: this.$t('common.status_turn_on') }
      ]
    },
    // errTime() {
    // 	const upT =
    // 		typeof this.onlineTime === 'number'
    // 			? this.onlineTime
    // 			: new Date(this.onlineTime)
    // 	const downT =
    // 		typeof this.offlineTime === 'number'
    // 			? this.offlineTime
    // 			: new Date(this.offlineTime)

    // 	if (this.dialogForm.aging === 1 && upT < downT) {
    // 		return false
    // 	} else if (this.dialogForm.aging === 2) {
    // 		return false
    // 	} else {
    // 		return true
    // 	}
    // },
    dataRule() {
      return {
        merchantId: [
          {
            required: true,
            message: this.$t('operation.please_choose_merchant'),
            trigger: 'change'
          }
        ],
        terminal: [
          {
            required: true,
            message: this.$t('common.please_choose'),
            trigger: 'change'
          }
        ],
        title: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips1'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: this.$t('operation.limit100'),
            trigger: 'blur'
          }
        ],
        titleEn: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips1'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: this.$t('operation.limit100'),
            trigger: 'blur'
          }
        ],
        titleTh: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips1'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: this.$t('operation.limit100'),
            trigger: 'blur'
          }
        ],
        titleVi: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips1'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: this.$t('operation.limit100'),
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips3'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 2000,
            message: this.$t('operation.limit2000'),
            trigger: 'blur'
          }
        ],
        contentEn: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips3'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 2000,
            message: this.$t('operation.limit2000'),
            trigger: 'blur'
          }
        ],
        contentTh: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips3'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 2000,
            message: this.$t('operation.limit2000'),
            trigger: 'blur'
          }
        ],
        contentVi: [
          {
            required: true,
            message: this.$t('operation.announcement.input_tips3'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 2000,
            message: this.$t('operation.limit2000'),
            trigger: 'blur'
          }
        ],
        tag: [
          {
            required: true,
            message: this.$t('common.please_choose'),
            trigger: 'blur'
          }
        ],
        aging: [
          {
            required: true,
            message: this.$t('common.please_choose'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    onlineTime: {
      handler(newV, oldV) {
        const up = this.onlineTime
        const down = this.offlineTime
        const U = dayjs(up).format('YYYY-MM-DD ')
        const D = dayjs(down).format('YYYY-MM-DD ')
        const selectableRange = (() => {
          const upT = new Date(up)
          const hour = upT.getHours()
          const minute = upT.getMinutes()
          const second = upT.getSeconds()
          return U === D
            ? [`${hour}:${minute}:${second} - 23:59:59}`]
            : ['00:00:00 - 23:59:59']
        })()
        this.dateEnd = {
          selectableRange: selectableRange,
          disabledDate(time) {
            return time.getTime() < newV - 24 * 60 * 60 * 1000
          }
        }
      },
      deep: true
    },
    offlineTime: {
      handler(newV, oldV) {
        const up = this.onlineTime
        const down = this.offlineTime
        const U = dayjs(up).format('YYYY-MM-DD ')
        const D = dayjs(down).format('YYYY-MM-DD ')
        const selectableRange = (() => {
          const upT = new Date(up)
          const hour = upT.getHours()
          const minute = upT.getMinutes()
          const second = upT.getSeconds()
          return U === D
            ? [`${hour}:${minute}:${second} - 23:59:59}`]
            : ['00:00:00 - 23:59:59']
        })()
        this.dateEnd = {
          selectableRange: selectableRange,
          disabledDate(time) {
            return (
              time.getTime() <
              new Date(up).getTime() - 24 * 60 * 60 * 1000
            )
          }
        }
      },
      deep: true
    },
    'queryData.opType': {
      handler(newV, oldV) {
        this.queryData.opName = ''
      }
    }
  },
  mounted() {
    if (!this.$store.getters.isZk) {
      this.queryData.merchantId = this.$store.getters.merchantInfo.id
      this.loadData()
    }
  },
  methods: {
    validateUpTime(rule, value, callback) {
      const up = dayjs(this.onlineTime).unix()
      const down = dayjs(this.offlineTime).unix()
      if (!this.onlineTime) {
        return callback(this.$t('common.please_choose'))
      }
      if (up >= down && this.dialogForm.aging === 1) {
        return callback(this.$t('operation.client_banner.input_tips1'))
      }
      callback()
    },
    validateDownTime(rule, value, callback) {
      const up = dayjs(this.onlineTime).unix()
      const down = dayjs(this.offlineTime).unix()
      if (!this.offlineTime) {
        return callback(this.$t('common.please_choose'))
      }
      if (up >= down) {
        return callback(this.$t('operation.client_banner.input_tips2'))
      }
      callback()
    },
    // 改变列表条数
    handleSizeChange(value) {
      this.pageNum = 1
      this.pageSize = value
      this.loadData()
    },
    handleCurrentChange(value) {
      this.pageNum = value
      this.loadData()
    },
    search() {
      this.pageNum = 1
      this.loadData()
    },
    handleMerchantIdChange() {
      this.dialogForm.title = ''
      this.dialogForm.titleEn = ''
      this.dialogForm.titleTh = ''
      this.dialogForm.titleVi = ''
      this.dialogForm.content = ''
      this.dialogForm.contentEn = ''
      this.dialogForm.contentTh = ''
      this.dialogForm.contentVi = ''
      this.$refs.formSub.clearValidate([
        'contentVi',
        'contentTh',
        'contentEn',
        'content',
        'titleVi',
        'titleTh',
        'titleEn',
        'title'
      ])
    },
    filterLanguages(lang) {
      return this.merchantInfoA?.languages
        ? this.merchantInfoA?.languages?.indexOf(lang) !== -1
        : false
    },
    change(val) { },
    loadData() {
      const params = {
        ...this.queryData,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }
      if (params?.terminal?.length) {
        params.terminal = params.terminal.join(',')
      }
      for (const k in params) {
        if (
          params[k] === '' ||
          params[k] === undefined ||
          (Array.isArray(params[k]) && !params[k].length)
        ) {
          delete params[k]
        }
      }
      this.list = []
      this.loading = true
      this.$api
        .getOperateConfigAnnouncementSelectAll(params)
        .then((res) => {
          if (res?.code === 200) {
            const { record, totalRecord } = res.data || {}
            this.list = Array.isArray(record)
              ? Object.freeze(record)
              : []
            this.total = totalRecord || 0
          } else {
            this.$message({
              message: res?.msg,
              type: 'error'
            })
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    changeTime(val) {
      // this.onlineTime = val
    },
    openCreateOrEditDialog(row) {
      if (row) {
        this.rowData = { ...row }
        this.dialogType = this.$t('common.edit')
        this.dialogForm = Object.assign({}, row)
        this.onlineTime = row.upTime
        this.offlineTime = row.downTime
        this.dialogForm.terminal = row.terminal.split(',') || []
        this.dialogForm.display = row.display || []
      } else {
        this.dialogType = this.$t('common.add')
        this.dialogForm = {
          merchantId: '',
          tag: 1,
          aging: 1,
          title: '',
          titleEn: '',
          titleTh: '',
          titleVi: '',
          content: '',
          contentEn: '',
          contentTh: '',
          contentVi: '',
          status: 0,
          terminal: this.loginDeviceType.map((i) => i.code),
          display: []
        }
        if (!this.$store.getters.isZk) {
          this.dialogForm.merchantId = this.$store.getters.merchantInfo.id
        } else {
          this.dialogForm.merchantId = undefined
        }
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.formSub.clearValidate()
      })
    },
    subAddOrEidt() {
      const startTime = this.onlineTime
      const endTime = this.offlineTime
      this.$refs.formSub.validate((valid) => {
        if (valid) {
          const params = { ...this.dialogForm }

          params.terminal = this.dialogForm.terminal.join(',')
          if (!params.terminal) {
            params.terminal = this.loginDeviceType
              .map((i) => i.code)
              .join(',')
          }
          if (this.dialogForm.aging === 1) {
            params.upTime = startTime
              ? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
              : undefined
            params.downTime = endTime
              ? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
              : undefined
          } else if (this.dialogForm.aging === 2) {
            params.downTime = undefined
            params.upTime = startTime
              ? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
              : undefined
          }
          if (this.dialogType === this.$t('common.edit')) {
            params.id = this.rowData.id
          }
          this.getOperateConfigAnnouncementSave(params)
        }
      })
    },
    getOperateConfigAnnouncementSave(val) {
      this.loading = true
      const sub =
        this.dialogType === this.$t('common.add')
          ? this.$api.getOperateConfigAnnouncementSave
          : this.$api.getOperateConfigAnnouncementUpdate
      sub(val)
        .then((res) => {
          const message =
            this.dialogType === this.$t('common.add')
              ? this.$t('common.add_success')
              : this.$t('common.edit_success')
          this.$message({
            message: message,
            type: 'success'
          })
          this.loadData()

          this.dialogFormVisible = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    clear() {
      this.$refs.formSub.resetFields()
      this.onlineTime = Date.now()
      this.offlineTime = endTime
    },
    deleteBtn(row) {
      this.$confirm(
        `<strong>${this.$t(
          'operation.delete_tips'
        )}?</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
          'operation.warning_tips'
        )}</span>`,
        this.$t('common.success_tip'),
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.$api
            .getOperateConfigAnnouncementDelete({ id: row.id })
            .then((res) => {
              if (res?.code === 200) {
                this.$message({
                  message: this.$t('common.delete_success'),
                  type: 'success'
                })
                this.loadData()
              }
            })
        })
        .catch(() => { })
    },
    changeStatus(row) {
      const id = row.id
      const status = row.status === 0 ? 1 : 0
      this.$confirm(
        `<strong>${this.$t('operation.switch_status_tips1')}${status === 1
          ? this.$t('common.start_up')
          : this.$t('common.disabled')
        }${this.$t(
          'common.actions'
        )}?</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
          'operation.switch_status_tips2'
        )}</span>`,
        this.$t('common.success_tip'),
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.$api
            .getOperateConfigAnnouncementStatus({
              id: id,
              status: status
            })
            .then(() => {
              this.$message({
                message: this.$t('common.action_success'),
                type: 'success'
              })
              this.loadData()
            })
            .catch(() => { })
        })
        .catch(() => { })
    },
    reset() {
      this.queryData.terminal = []
      this.queryData.aging = undefined
      this.queryData.opType = '0'
      this.queryData.opName = undefined
      this.queryData.tag = undefined
      this.queryData.title = undefined
      this.queryData.merchantId = undefined
      this.queryData.status = undefined
      if (!this.$store.getters.isZk) {
        this.queryData.merchantId = this.$store.getters.merchantInfo.id
      }
      this.pageNum = 1
      this.loadData()
    },

    filterTerminal(val) {
      const arr = val ? val.split(',') : []
      if (arr.length) {
        return arr
          .map((item) => this.typeFilter(item, 'clientType'))
          .join(',')
      }
      return '-'
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .tagheight {
	.el-form-item__content,
	.el-select {
		width: 480px;
	}
}
// ::v-deep  .rempadding .el-dialog__body {
//   padding: 0;
//   padding-bottom: 30px;
//   .contentBox,
//   form {
//     padding: 0 20px;
//   }
// }

.tooltip-content {
	width: 250px;
}
.tooltip-trigger {
	white-space: nowrap;
	text-overflow: ellipsis;
	overflow: hidden;
}
.el-form-item__error {
	padding-bottom: 4px;
}
::v-deep .el-input-group__prepend {
	background-color: #fff;
}
.dialog_style {
	::v-deep .el-dialog__header {
		// padding-bottom: 0;
		border-bottom: 1px solid #dcdfe6;
		.header_style {
			display: flex;
			justify-content: space-between;
			.text_left {
				font-weight: 700;
			}
			.text_right {
				color: #909399;
				span {
					color: #ff3b30;
				}
			}
		}
	}
	::v-deep .el-dialog__body {
		// padding: 0;
		form {
			// margin: 0 15px;
			// margin-top: 20px;
			// padding: 15px 15px 0;
			// border: 1px solid #dcdfe6;
			// border-radius: 5px;
			h4 {
				margin-top: 0;
			}
		}
	}
	.dialog-footer {
		text-align: center;
	}
}

.vi_VN,
.en_US {
	.tagheight ::v-deep .el-form-item__content,
	.tagheight .el-select {
		width: 610px;
	}
}
</style>
